﻿using System.IO;

namespace ShpMerger
{
    public class DestFileWriter
    {
        private OneInfo oneInfo;

        public DestFileWriter()
        {
            oneInfo = new OneInfo();
        }

        /// <summary>
        /// add source file to dest file
        /// </summary>
        /// <param name="srcFile"></param>
        /// <param name="destFile"></param>
        public void AddSrcFile(string srcFile,string destFile)
        {
            //create binary stream
            FileStream Fsre = new FileStream(srcFile, FileMode.Open, 
                    FileAccess.Read);
            ExtendBinaryReader BRS = new ExtendBinaryReader(Fsre);
            FileStream Fdre = new FileStream(destFile, FileMode.Open, 
                    FileAccess.Read);
            ExtendBinaryReader BRD = new ExtendBinaryReader(Fdre);
            ShapeHeader sourceHeader = new ShapeHeader();
            ShapeHeader destHeader = new ShapeHeader();

            //merge file header from source file to dest
            sourceHeader.Read(BRS);
            destHeader.Read(BRD);
            destHeader.Merge(sourceHeader);
            Fdre.Close();

            //add each info from source file to dest
            //1. rewrite dest file header because of the file length and box
            FileStream Fdwr = new FileStream(destFile, FileMode.Open, 
                    FileAccess.ReadWrite);
            ExtendBinaryWriter BWD = new ExtendBinaryWriter(Fdwr);
            destHeader.Write(BWD);

            //2. go to last byte and add source info
            BWD.Seek(0, SeekOrigin.End);
            int writeCount=0;
            while (writeCount < sourceHeader.FileLength - 100)
            {
                oneInfo.AddInfo(BRS, BWD);
                writeCount += oneInfo.InfoHeader.InfoLength + 4;
            }
            Fsre.Close();
            Fdwr.Close();
        }

        /// <summary>
        /// create dest file and write a null header
        /// </summary>
        /// <param name="destFile"></param>
        public void InitDestFile(string destFile)
        {
            FileStream Fdrw = new FileStream(destFile, FileMode.Create, 
                FileAccess.ReadWrite);
            ExtendBinaryWriter BWD = new ExtendBinaryWriter(Fdrw);
            ShapeHeader destFileHeader = new ShapeHeader();
            destFileHeader.Write(BWD);
            Fdrw.Close();
        }
    }
}
